//
//  RYPatternLockView.m
//  PatternLock
//
//  Created by Ryan on 13-5-9.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "RYPatternLockView.h"

#define MATRIX_SIZE 3

@interface RYPatternLockView()

@property (nonatomic, retain) NSValue *trackPointValue;
@property (nonatomic, retain) NSMutableArray *dotViews;
@property (nonatomic, retain) NSMutableArray *paths;

@end

@implementation RYPatternLockView

@synthesize trackPointValue,dotViews,paths;
@synthesize delegate;

#pragma mark - UIView mehthods
- (void)awakeFromNib
{
    [super awakeFromNib];
    self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_patternLock@2x.png"]];
    //添加锁屏图案3*3
    for (int i=0; i<MATRIX_SIZE; i++) {
        for (int j=0; j<MATRIX_SIZE; j++) {
            UIImage *dotImage = [UIImage imageNamed:@"lock_off_patternLock@2x.png"];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:dotImage
                                                       highlightedImage:[UIImage imageNamed:@"lock_on_patternLock@2x.png"]];
            imageView.frame = CGRectMake(0, 0, dotImage.size.width/2, dotImage.size.height/2);
            imageView.userInteractionEnabled = YES;
            imageView.tag = j*MATRIX_SIZE + i + 1;
            [self addSubview:imageView];
            [imageView release];
        }
    }
}

- (void)layoutSubviews
{
    //划分9宫格，各模块对应的锁屏图案居中显示
    int w = self.frame.size.width/MATRIX_SIZE;
    int h = self.frame.size.height/MATRIX_SIZE;
    
    int i=0;
    for (UIView *view in self.subviews)
        if ([view isKindOfClass:[UIImageView class]]) {
            int x = w*(i/MATRIX_SIZE) + w/2;
            int y = h*(i%MATRIX_SIZE) + h/2;
            view.center = CGPointMake(x, y);
            i++;
        }
}

- (void)dealloc
{
    [paths release];
    [trackPointValue release];
    [dotViews release];
    [super dealloc];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    if (!trackPointValue)
        return;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 10.0);
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = {1, 0.58, 0.13, 0.5};
    CGColorRef color = CGColorCreate(colorspace, components);
    CGContextSetStrokeColorWithColor(context, color);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGPoint from;
    UIView *lastDot = nil;
    for (UIView *dotView in dotViews) {
        from = dotView.center;
        if (!lastDot)
            CGContextMoveToPoint(context, from.x, from.y);
        else
            CGContextAddLineToPoint(context, from.x, from.y);
        lastDot = dotView;
    }
    
    CGPoint pt = [trackPointValue CGPointValue];
    if(dotViews.count > 0)
        CGContextAddLineToPoint(context, pt.x, pt.y);
    
    CGContextStrokePath(context);
    CGColorSpaceRelease(colorspace);
    CGColorRelease(color);
    
    self.trackPointValue = nil;
}

#pragma mark - UIResponder methods
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.paths = [NSMutableArray array];
    self.dotViews = [NSMutableArray array];
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    UIView *touched = [self hitTest:pt withEvent:event];
    //滑动区域在锁屏页面里
    if(touched)
    {
        self.trackPointValue = [NSValue valueWithCGPoint:pt];
        [self setNeedsDisplay];
        
        if (touched != self) {
            BOOL found = NO;
            for (NSNumber *tag in paths) {
                found = tag.integerValue==touched.tag;
                if (found)
                    break;
            }
            if (found)
                return;
            
            [paths addObject:[NSNumber numberWithInt:touched.tag]];
            [dotViews addObject:touched];
            
            UIImageView* iv = (UIImageView*)touched;
            iv.highlighted = YES;
        }
    }
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // clear up hilite
    [dotViews removeAllObjects];
    
    for (UIView *view in self.subviews)
        if ([view isKindOfClass:[UIImageView class]])
            [(UIImageView*)view setHighlighted:NO];
    
    [self setNeedsDisplay];
    
    NSMutableString *password = [NSMutableString stringWithString:@""];
    // simple way to generate a key
    for (NSNumber *tag in paths) {
        [password appendFormat:@"%d", tag.integerValue];
    }
    [self.delegate didPatternLockFinishedWithPassword:password];
}


@end
